using B.S.DataBase.MyProject.Infrastructure.Implement;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyProject.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System.Reflection;
using MedicalPCTerminal.Read.API.Filters;
using Microsoft.OpenApi.Models;
using MedicalPCTerminal.Read.API.Common;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Caching.StackExchangeRedis;
using StackExchange.Redis;
using System.Configuration;
using ServiceManagement.Consul;
namespace MedicalPCTerminal.Read.API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            // 添加CORS策略
            builder.Services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                });
            });

            // 添加SignalR
            builder.Services.AddSignalR();

            ////
            //builder.Services.AddDbContext<SDbContext>(x => x.UseMySql(builder.Configuration.GetConnectionString("Db"), ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("Db"))));

            builder.Services.AddStackExchangeRedisCache(options =>
            {
                // ��������ѡ��
                options.ConfigurationOptions = ConfigurationOptions.Parse(builder.Configuration["Redis:Configuration"]);

                // ʵ����������
                options.InstanceName = builder.Configuration["Redis:InstanceName"];

                // �߼����Ӳ���
                options.ConfigurationOptions.ConnectTimeout = 3000;  // ���ӳ�ʱ3��
                options.ConfigurationOptions.SyncTimeout = 5000;     // ͬ����ʱ5��
                options.ConfigurationOptions.AbortOnConnectFail = false; // ����ʧ�ܲ���ֹ
            });

            ////����redis����
            //builder.Services.AddSingleton<IConnectionMultiplexer>(sp => ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")));


            builder.Configuration.Register();

            // ��ȡ���ݿ������ַ���
            var connectionString = builder.Configuration.GetConnectionString("Db");
            //sqlsugar
            builder.Services.AddScoped<SqlSugarContext>();

            //ȫ���쳣������
            builder.Services.AddControllers(c => c.Filters.Add<MyExceptionFilter>());
            //�ִ�
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

            //ע���н���
            builder.Services.AddMediatR(x => x.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

            //ע��automapper
            builder.Services.AddAutoMapper(typeof(AutoMapperFilePro));
            //��ȡ�����ļ�
            var jwtSettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
            //��Ȩ��֤��ʹ��JWT��
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // ˽Կ
                //var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
                var secreByte = Encoding.UTF8.GetBytes(jwtSettings.secretByte);
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    // ��֤������
                    ValidateIssuer = true,
                    // ��������Ϣ
                    ValidIssuer = jwtSettings.Issuer,

                    // ��֤������
                    ValidateAudience = true,
                    // ������
                    ValidAudience = jwtSettings.Audience,

                    // ��֤�Ƿ����
                    ValidateLifetime = true,

                    // ��֤˽Կ
                    IssuerSigningKey = new SymmetricSecurityKey(secreByte)

                };
            });
            // ����Swagger
            builder.Services.AddSwaggerGen(o =>
            {
                // ��ȡ��ǰ���򼯵�����
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                // ��ȡXML�ļ�������·��
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                // ����XMLע���ļ�
                o.IncludeXmlComments(xmlPath);

                // ֧������ע����ʾ
                o.CustomSchemaIds(type => type.FullName);
                // ��ʾ ��Ȩ��Ϣ
                o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
                {
                    Description = "����JWT��ȨToken��Bearer Tokenֵ",
                    Name = "Authorization",
                    In = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[]
                        {

                        }
                    }
                });
            });

            var app = builder.Build();
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            // Configure the HTTP request pipeline.
            //if (app.Environment.IsDevelopment())
            //{
                app.UseSwagger();
                app.UseSwaggerUI();
            //}

            // ��Ȩ
            app.UseAuthentication();

            app.UseAuthorization();

            app.MapControllers();

            // 添加静态文件支持
            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.Run();
        }
    }
}
